package cn.fyl.org.controller;

import cn.fyl.basic.util.JsonResult;
import cn.fyl.basic.util.PageList;
import cn.fyl.org.domain.Department;
import cn.fyl.org.query.DepartmentQuery;
import cn.fyl.org.service.IDepartmentService;
import cn.fyl.system.listener.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/deptTree")
    @PreAuthorize(name = "部门树",sn = "department:Tree") //value后面用来做权限校验
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @PreAuthorize(name = "部门列表",sn = "department:getAll") //value后面用来做权限校验
    public List<Department> findAll(){
        return departmentService.loadAll();
    }

    /**
     * 查询一个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize(name = "获取部门",sn = "department:get") //value后面用来做权限校验
    public Department findById(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除部门",sn = "department:delete") //value后面用来做权限校验
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 添加和修改操作
     * @param department
     * @return
     */
    @PostMapping
    @PreAuthorize(name = "部门保存",sn = "department:save") //value后面用来做权限校验
    public JsonResult save(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }

    }

    /**
     * 分页查询
     * @param departmentQuery
     * @return
     */
    @PutMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        try {
            return departmentService.queryData(departmentQuery);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageList<Department>();
        }
    }

    @PatchMapping
    public JsonResult patchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.patchDelete(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }
}
